package com.atguigu.springcloud;

import com.alibaba.druid.util.StringUtils;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymenService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ：jjt8024
 * @date ：Created in 2020/12/5 11:21
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymenService paymenService;

    @Value("${server.port}")
    private String port;


    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
         int result  = paymenService.create(payment);
         log.info("****插入結果："+result);
         if(result>0){
             return new CommonResult(200,"插入成功！");
         }else{
             return new CommonResult(500,"插入失敗！");
         }
    }

  /*  @GetMapping("/payment/get/{id}")
    public CommonResult  getPaymentById(@PathVariable("id") Long id){
         Payment payment = paymenService.getPaymentById(id);
         if(payment!=null){
             return new CommonResult(200,"查詢成功！ port:"+port,payment);
         }else{
             return new CommonResult(500,"查詢失敗！");
         }

    }*/

    @GetMapping("/payment/get/{id}")
    @HystrixCommand(fallbackMethod = "getPaymentByIdHystrix")
    public CommonResult  getPaymentById(@PathVariable("id") Long id){
//         Payment payment = paymenService.getPaymentById(id);
         if(id != 2){
             return new CommonResult(200,"查詢成功！ port:"+port,id);
         }else{
             throw  new RuntimeException("查詢失敗！没有该"+id+"信息！");
         }

    }

    public CommonResult getPaymentByIdHystrix(@PathVariable("id") Long id){
        return new CommonResult(500,"系统内部异常，请联系管理员");
    }

    @PostMapping("/payment/getAllPayment")
    public CommonResult  getPayment(){
        CommonResult result = new CommonResult();
        List<Payment> list  =  paymenService.getAllPayments();
        result.setData(list);
        result.setCode(200);
        result.setMessage("调用成功！");
        return  result;
    }


    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }


}
